package com.android.webttest.broadcast;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.android.webttest.R;

public class BootCompletedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 检查是否是系统启动完成的广播
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            // 触发促销活动的通知
            showPromotionNotification(context);
        }
    }

    private void showPromotionNotification(Context context) {
        // 创建通知渠道（适用于Android 8.0及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "promotion_channel_id",
                    "促销活动",
                    NotificationManager.IMPORTANCE_HIGH
            );
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "promotion_channel_id")
                .setSmallIcon(R.drawable.ic_promotion)
                .setContentTitle("促销活动提醒")
                .setContentText("我们的应用有新的促销活动，快来查看吧！")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

        // 显示通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        // 显示通知前检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
                    == PackageManager.PERMISSION_GRANTED) {
                notificationManager.notify(1, builder.build());
            } else {
                // 权限未授予，无法发送通知（可记录日志或尝试其他方式提醒用户）
                // 注意：BroadcastReceiver 中不能直接请求权限
            }
        } else {
            // Android 12 及以下不需要此权限
            notificationManager.notify(1, builder.build());
        }
    }
}